package service;

import JDBC.DBUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import method.ItemCollect;
import method.ItemInformation;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * @author Gao Shiwei
 * this class can show all item-collections of the user
 */
@WebServlet(name = "AllCollection")
public class AllCollection extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.addHeader("Access-Control-Allow-Credentials", "true");
        HttpSession session = req.getSession();
        String PhoneNumber = (String) session.getAttribute("PhoneNumber");
        ItemCollect[] Collect = DBUtils.QueryItemCollect("PhoneNumber", PhoneNumber);
        JsonObject Container = new JsonObject();

        JsonArray array = new JsonArray();

        JsonObject oneItem = new JsonObject();
        if (Collect.length != 0) {
            for (int i = 0; i < Collect.length; i++) {
                oneItem.addProperty("ItemID", Collect[i].getItemID());
                ItemInformation[] Item = DBUtils.QueryItemInformation("ItemID", Collect[i].getItemID());
                oneItem.addProperty("ItemName", Item[0].getItemName());
                oneItem.addProperty("ItemPrice", Item[0].getItemPrice());
                oneItem.addProperty("ItemType", Item[0].getItemType());
                oneItem.addProperty("ItemQuantity", Item[0].getItemQuantity());
                oneItem.addProperty("ItemDescription", Item[0].getItemDescription());
                String picture = DBUtils.QueryItemPicture(Collect[i].getItemID());
                if (picture != null)
                    picture.replace("\\", "\\\\");
                oneItem.addProperty("Picture", picture);
                array.add(oneItem);
                oneItem = new JsonObject();
            }
            Container.add("Collet", array);
            PrintWriter out = resp.getWriter();
            out.println(Container);
            out.flush();
            out.close();
        }else{
            Container.add("Collet", null);
            PrintWriter out = resp.getWriter();
            out.println(Container);
            out.flush();
            out.close();
        }
    }
}
